package com.perfma.xtest.zsai;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

/**
 * @author: junhui.si
 * @date: 2024-03-08 17:13
 **/
public class SignAndSend {
    private static final String CONTENT_CHARSET = "UTF-8";
    private static final String HMAC_ALGORITHM = "HmacSHA1";

    public static String encodePayloadString(String payloadStr) throws UnsupportedEncodingException {
        String encodePayload = "";
        byte[] bytes = payloadStr.getBytes(CONTENT_CHARSET);
        String base64Encode = Base64.encode(bytes);
        encodePayload = URLEncoder.encode(base64Encode, CONTENT_CHARSET);
        return encodePayload;
    }

    public static String sign(String source, String appSecret, String payload, String timeStr) throws Exception {
        String signStr = "x-date: " + timeStr + "\n" + "source: " + source + "\n" + "x-custom-payload: " + payload;
        //获取接口签名
        String sig = null;
        Mac mac1 = Mac.getInstance(HMAC_ALGORITHM);
        byte[] hash;
        SecretKeySpec secretKey = new SecretKeySpec(appSecret.getBytes(CONTENT_CHARSET), mac1.getAlgorithm());
        mac1.init(secretKey);
        hash = mac1.doFinal(signStr.getBytes(CONTENT_CHARSET));
        sig = Base64.encode(hash);
        System.out.println("signValue--->" + sig);
        return sig;
    }

    public static String auth(String source, String appKey, String appSecret, String encodePayload, String timeStr) throws Exception {
        String sig = sign(source, appSecret, encodePayload, timeStr);
        String authStr = "hmac username=\"" + appKey + "\", algorithm=\"hmac-sha1\", headers=\"x-date source x-custom-payload\", signature=\"" + sig + "\"";
        System.out.println("authStr --->" + authStr);
        return authStr;
    }

    public static String doGet(String url, String appKey, String appSecret, String source, String payloadStr) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        URIBuilder uriBuilder = null;
        String result = "";
        try {
            //获取当前 GMT 时间
            Calendar cd = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
            sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
            String timeStr = sdf.format(cd.getTime());
            String encodePayload = encodePayloadString(payloadStr);
            String authStr = auth(source, appKey, appSecret, encodePayload, timeStr);

            //仅示例，不同接口入参不一样
            uriBuilder = new URIBuilder(url);
            uriBuilder.setParameter("knowledgeId", "");
            uriBuilder.setParameter("articleId", "");
            uriBuilder.setParameter("spaceId", "aiteam_test");

            HttpGet httpGet = new HttpGet(uriBuilder.build());
            httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpGet.setHeader("Source", source);
            httpGet.setHeader("X-Date", timeStr);
            httpGet.setHeader("Authorization", authStr);
            httpGet.setHeader("X-Custom-Payload", encodePayload);

            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (uriBuilder != null) {
                uriBuilder.clearParameters();
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static String doPost(String url, String appKey, String appSecret, String source, String payloadStr) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        URIBuilder uriBuilder = null;
        String result = "";
        try {
            //获取当前 GMT 时间
            Calendar cd = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
            sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
            String timeStr = sdf.format(cd.getTime());
            String encodePayload = encodePayloadString(payloadStr);
            String authStr = auth(source, appKey, appSecret, encodePayload, timeStr);

            uriBuilder = new URIBuilder(url);
            HttpPost httpPost = new HttpPost(uriBuilder.build());
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.setHeader("Source", source);
            httpPost.setHeader("X-Date", timeStr);
            httpPost.setHeader("Authorization", authStr);
            httpPost.setHeader("X-Custom-Payload", encodePayload);

            //仅示例，不同接口入参不一样
            //入参为我们的问题，query:””
            httpPost.setEntity(new StringEntity("{\n" +
                    "    \"spaceId\":  \"aiteam_test\",\n" +
                    "    \"catalogId\": ,\n" +
                    "    \"title\": \"test-create-atiicle-1334\",\n" +
                    "    \"content\": \"test-create-atiicle-1334-ABA\",\n" +
                    "    \"permanent\": 1\n" +
                    "}\n" +
                    "\n"));

            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (uriBuilder != null) {
                uriBuilder.clearParameters();
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
